<template>
  <div v-loading="loading" class="b-cont">
    <!--点击编辑后，显示保存按钮-->
    <div v-if="showSaveButton" class="b-cont__handle">
      <el-button @click="editCancel">取消</el-button>
      <el-button v-debounce="editConfirm" type="primary">保存</el-button>
    </div>

    <!--list中存放的是显示的数据列表-->
    <template v-for="(mainItem, mainIndex) in list" :key="mainIndex">
      <Sections :title="mainItem.name" class="b-cells" content-height="auto">
        <el-form :model="editForm"
                 :rules="currentEditRules" :ref="`editForm${mainIndex}`"
                 :validate-on-rule-change="false" class="el-form--flex"
                 label-position="left" label-width="100px">
          <!-- 当 v-if 和 v-for 同时存在于一个元素上的时候，v-if 会首先被执行 -->
          <template v-for="(item, index) in mainItem.list" :key="index">
            <el-form-item v-if="getShowValue(item)" :prop="item.fieldName"
                          :class="[{'is-block': isBlockShowField(item)}, `is-${item.formType}`]">
              <template v-slot:label>
                <span>{{ item.name }}</span>
              </template>
              <!-- 可编辑的情况下 -->
              <template v-if="item.isEdit">
                <WkField :item="item" :index="index" :field-from="editForm" :ignore-fields="ignoreFields"
                         @change="formChange">
                  <!--<template slot-scope="{ data, index }">-->
                  <template v-slot:default="{ data, index }">
                    <el-select v-if="data.formType === 'business_status'"
                               v-model="editForm[data.fieldName]" style="width: 100%;" clearable>
                      <el-option v-for="(optionItem, optionIndex) in getFieldOption(data)" :key="optionIndex"
                                 :label="optionItem.name"
                                 :value="optionItem.value"/>
                    </el-select>
                    <el-select v-if="data.fieldName == 'status'" v-model="editForm[data.fieldName]" style="width: 100%;">
                      <el-option v-for="item in data.setting" :key="item.value"
                                 :label="item.name" :value="item.value"/>
                    </el-select>
                    <CrmRelativeCell v-else-if=
                                         "data.formType === 'contacts'
                                         || data.formType === 'customer'
                                         || data.formType === 'contract'
                                         ||data.formType === 'business'"
                                     :relative-type="data.formType"
                                     :value="editForm[data.fieldName]"
                                     @value-change="arrayValueChange($event, data)"/>
                    <XhProuctCate v-else-if="data.formType === 'category'"
                                  :value="editForm[data.fieldName]"
                                  @value-change="arrayValueChange($event, data)"/>
                    <el-select v-if="data.fieldName == 'invoiceType'" v-model="editForm[data.fieldName]"
                               style="width: 100%;">
                      <el-option v-for="item in invoiceTypeOptions" :key="item.value"
                                 :label="item.name" :value="item.value"/>
                    </el-select>
                  </template>
                </WkField>
              </template>
              <!-- 不可编辑的情况下 -->
              <template v-else>
                <!--如果地图显示组件-->
                <div v-if="item.formType === 'map_address'" :gutter="0" wrap="wrap">
                  <div :span="0.5" class="b-cell">
                    <flexbox class="b-cell-b">
                      <div class="b-cell-name">定位</div>
                      <div class="b-cell-value" style="color: #2362FB;cursor: pointer;" @click="checkMapView(item)">
                        {{ item.value.location }}
                      </div>
                    </flexbox>
                  </div>
                  <div :span="0.5" class="b-cell">
                    <flexbox class="b-cell-b">
                      <div class="b-cell-name">区域</div>
                      <div class="b-cell-value">{{ item.value.address }}</div>
                    </flexbox>
                  </div>
                  <div :span="0.5" class="b-cell">
                    <flexbox class="b-cell-b">
                      <div class="b-cell-name">详细地址</div>
                      <div class="b-cell-value">{{ item.value.detailAddress }}</div>
                    </flexbox>
                  </div>
                </div>
                <flexbox v-else :class="{'can-check':isModule(item)}" align="stretch" style="width: 100%;"
                         class="form-item__value">
                  <WkFieldView :props="item" :form-type="item.formType" :value="item.value"
                               :ignore-fields="ignoreFields">
                    <!--<template slot-scope="{ data }">-->
                    <template v-slot:default="{ data }">
                      <span v-if="data.formType === 'business_type'">{{ detail ? detail.typeName : '' }}</span>
                      <span v-else-if="data.formType === 'business_status'">{{ detail ? detail.statusName : '' }}</span>
                      <span v-else-if="data.formType === 'category'">{{ detail ? detail.categoryName : '' }}</span>
                      <span v-else-if="data.formType === 'receivables_plan'">{{ detail ? detail.planNum : '' }}</span>
                      <span v-else-if="ignoreFields.includes(data.props.field) && data.props.field === 'status'">
                      {{ getSelectShowValue(data) }}
                    </span>
                      <span v-else @click="checkModuleDetail(data)">{{ getCommonShowValue(data) }}</span>
                    </template>
                  </WkFieldView>

                  <i v-if="getEditAuth(item)" class="wk wk-edit form-item__edit" @click.stop="editClick(item, index)"/>
                </flexbox>
              </template>
            </el-form-item>
          </template>
        </el-form>
      </Sections>
    </template>

    <slot/>
    <MapView v-if="showMapView"
             :title="mapViewInfo.title"
             :lat="mapViewInfo.lat" :lng="mapViewInfo.lng"
             @hidden="showMapView=false"/>

    <CRMFullScreenDetail :visible="showFullDetail"
                         :id="fullDetailId"
                         :crm-type="fullDetailType"/>
  </div>
</template>

<script setup>
import {filedGetInformationAPI, filedUpdateTableFieldAPI} from '/src/api/crm/common.js'

import {useHookCustomFields} from "@/mixins/HookCustomFields.js";
import CRMFullScreenDetail from '/src/components/CRMFullScreenDetail.vue'
import {computed, getCurrentInstance, nextTick, onBeforeUnmount, onMounted, ref, toRef, watch} from "vue";
import crmTypeModel from '/src/views/crm/model/crmTypeModel.js'
import {objDeepCopy} from '/src/utils/index.js'
import {isArray, isObject, isEmpty} from '/src/utils/types.js'
import {getFormFieldShowName} from '/src/components/NewCom/WkForm/utils.js'
import {useErpUserStore} from "../../../../store/modules/usererp.js";
import {
  CrmRelativeCell,
  XhProuctCate,
} from '/src/components/CreateCom/index.js'
import WkFieldView from '/src/components/NewCom/WkForm/WkFieldView.vue'
import WkField from '/src/components/NewCom/WkForm/WkField.vue'
import Sections from '../Sections.vue'
import MapView from '/src/components/MapView.vue' // 地图详情
import {useHookGenerateRules} from "components/NewCom/WkForm/HookGenerateRules.js";


// 引入消息总线
const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus


// 客户管理 的 基本信息
defineOptions({
  name: 'CRMEditBaseInfo',
})

// todo whf 有些组件没有props.action，所以会报错
// const hookCustomFields = useHookCustomFields(toRef(props.action))
const hookCustomFields = useHookCustomFields()
const hookGenerateRules = useHookGenerateRules()

const props = defineProps({
  // 模块ID
  id: [String, Number],
  poolId: [String, Number],
  isSeas: {
    type: Boolean,
    default: false
  },
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  },
  // 没有值就是全部类型 有值就是当个类型
  crmType: {
    type: String,
    default: ''
  },
  // 固定字段的数据
  filedList: Array,
  // 系统消息之前的数据
  otherList: Array,
  // 忽略的字段直接输出
  ignoreFields: {
    type: Array,
    default: () => {
      return []
    }
  }
})


const loading = ref(false)


// 地图详情信息
const mapViewInfo = ref({})
const showFullDetail = ref(false)
const fullDetailId = ref('')
const fullDetailType = ref('')

const editRules = ref({}) // 全字段规则
const currentEditRules = ref({}) // 当前编辑字段规则

const allForm = ref({}) // 用于逻辑表单刷新
const editOptions = ref({})
const editFieldData = ref([]) // baseList 的引用
const invoiceTypeOptions = ref([{
  name: '增值税专用发票',
  value: 1
}, {
  name: '增值税普通发票',
  value: 2
}, {
  name: '国税通用机打发票',
  value: 3
}, {
  name: '地税通用机打发票',
  value: 4
}, {
  name: '收据',
  value: 5
}])


// 从store中拿到crm权限
const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm
})

watch(() => props.id, (val) => {
  if (!props.filedList) {
    getBaseInfo(true)
  }
})

function created() {
  bus.on('crm-detail-update', (data) => {
    getBaseInfo(false)
  })
}

created()

onBeforeUnmount(() => {
  bus.off('crm-detail-update')
})




const list = ref([])
watch(() => props.filedList, () => {
  list.value = props.filedList
})
onMounted(() => {
  if (props.filedList) {
    list.value = props.filedList
  } else {
    getBaseInfo(true)
  }
})
/**
 * 获取基础信息
 */
function getBaseInfo(load) {
  loading.value = !!load
  const params = {
    types: crmTypeModel[props.crmType],
    id: props.id
  }

  // 如果有公海id，需上传确定展示字段
  if (props.poolId) {
    params.poolId = props.poolId
  }

  filedGetInformationAPI(params).then(res => {
    const baseList = []
    const systemList = []

    const resData = res.data.data || []
    // 编辑用信息
    const editFieldData1 = []
    const editRules1 = {}

    resData.forEach(item => {
      // todo whf 这个sysInformation能否改正常点
      if (item.sysInformation == 1) {
        systemList.push(item)
      } else if (item.formType !== 'product') {
        // 不展示产品
        baseList.push(item)
      }
    })
    console.log("systemList", systemList)
    console.log("baseList", baseList)

    // 逻辑表单逻辑
    const assistIds = hookCustomFields.getFormAssistIds([baseList])
    console.log("assistIds", assistIds)
    baseList.forEach(item => {
      hookCustomFields.getFormItemDefaultProperty(item, false)
      item.show = !assistIds.includes(item.formAssistId)

      if (props.ignoreFields.includes(item.field)) {
        // 防止影响普通单选的验证方式 该方法必须在获取值之上
        delete item.optionsData
      }

      const canEdit = hookCustomFields.getItemIsCanEdit(item, 'update')
      // 是否能编辑权限
      const copyItem = objDeepCopy(item)
      if (item.show && canEdit) {
        editRules1[item.field] = hookGenerateRules.getRules(copyItem)
      }

      // 是否可编辑
      item.disabled = !canEdit

      // 特殊字段允许多选
      hookCustomFields.getItemRadio(item, item)

      // 表格为了展示，提前处理为编辑数据
      if (item.formType === 'detail_table') {
        if (!isEmpty(item.value)) {
          item.value = hookCustomFields.getItemValue(item, null, 'update')
        }
        allForm.value[item.field] = item.value
      } else {
        // copyItem 避免修改原始item.value
        allForm.value[item.field] = hookCustomFields.getItemValue(copyItem, null, 'update')
      }

      editFieldData1.push(item)
    })

    // 编辑逻辑赋值
    editFieldData.value = editFieldData1
    editRules.value = editRules1

    if (props.otherList) {
      list.value = [
        {
          name: '基本信息',
          list: baseList
        },
        ...props.otherList,
        {
          name: '系统信息',
          list: systemList
        }
      ]
    } else {
      list.value = [
        {
          name: '基本信息',
          list: baseList
        },
        {
          name: '系统信息',
          list: systemList
        }
      ]
    }

    console.log("list", list)
    editCancel()
    loading.value = false
  }).catch((e) => {
    console.log(e)
    loading.value = false
  })
}


const editForm = ref({})


/**
 * change
 */
function formChange(field, index, value, valueList) {
  if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
      field.remark === 'options_type' &&
      field.optionsData) {
    const {
      fieldForm,
      fieldRules
    } = hookCustomFields.getFormContentByOptionsChange([editFieldData.value], {...allForm.value, ...editForm.value}, editRules.value, null, 'update')

    const editForm = {}
    const currentEditRules = {}

    editFieldData.value.forEach(item => {
      // 重新获取当前可编辑字段的值和规则
      if (item.show && item.isEdit) {
        editForm[item.field] = fieldForm[item.field]
        currentEditRules[item.field] = fieldRules[item.field]
      }

      // 不展示的字段，但处在可编辑状态，置为不能编辑
      if (!item.show && item.isEdit) {
        item.isEdit = false
      }
    })
    editForm.value = editForm
    currentEditRules.value = currentEditRules
  }
}


// 控制展示地图详情
const showMapView = ref(false)
/**
 * 查看地图详情
 */
function checkMapView(item) {
  if (isObject(item.value) && !isEmpty(item.value.location)) {
    mapViewInfo.value = {
      title: item.value.location,
      lat: item.value.lat,
      lng: item.value.lng
    }
    showMapView.value = true
  }
}

/**
 * 客户的模块类型
 */
function isModule(item) {
  return [
    'customer',
    'business',
    'contract',
    'contacts'].includes(item.formType)
}

/**
 * 是整行展示字段
 */
function isBlockShowField(item) {
  return [
    'map_address',
    'file',
    'detail_table'].includes(item.formType)
}

/**
 * 特殊格式数据获取展示名称
 */
function getModuleName(item) {
  // 模块数据
  const moduleField = {
    customer: 'customerName',
    business: 'businessName',
    contract: 'contractNum',
    contacts: 'name'
  }[item.formType]

  if (moduleField) {
    let data = {}
    if (isObject(item.value)) {
      data = item.value
    } else if (isArray(item.value) && item.value.length > 0) {
      data = item.value[0]
    }
    return data[moduleField] || ''
  }

  // 常规对象数据
  const field = {
    category: 'categoryName'
  }[item.formType]
  return item.value ? item.value[field] : ''
}

/**
 * 获取下拉数据
 */
function getFieldOption(item) {
  const editData = editOptions.value[item.fieldName]
  let setting = []
  if (editData) {
    if (item.formType === 'select' || item.formType === 'checkbox') {
      if (editData.setting.length > 0 && typeof editData.setting[0] == 'string') {
        setting = editData.setting.map(element => {
          return {name: element, value: element}
        })
      } else {
        setting = editData.setting
      }
    } else if (item.formType === 'business_status') {
      setting = editData.setting.map(element => {
        element.value = element.statusId
        return element
      })
    }
  }

  return setting
}

/**
 * 获取非附件类型的展示值
 */
function getCommonShowValue(item) {
  console.log("getCommonShowValue",item)
  if (isModule(item)) {
    return getModuleName(item)
  } else {
    const field = item.props
    if (field.fieldName === 'invoiceType') {
      const dataItem = invoiceTypeOptions.value.find(o => o.value == item.value)
      return dataItem ? dataItem.name : ''
    }
    return getFormFieldShowName(item.formType, item.value, '', item)
  }
}

/**
 * 查看详情
 */
function checkModuleDetail(data) {
  const dataValue = data.value
  if (isModule(data)) {
    let id = ''
    if (isObject(dataValue)) {
      id = dataValue[`${data.formType}Id`]
    } else if (isArray(dataValue) && dataValue.length > 0) {
      id = dataValue[0][`${data.formType}Id`]
    }

    if (id) {
      fullDetailType.value = data.formType
      fullDetailId.value = id
      showFullDetail.value = true
    }
  }
}

/**
 * 编辑权限逻辑
 * 下面列出来的字段是不能编辑的
 */
function getEditAuth(item) {
  if (props.isSeas) {
    return false
  }
  if (props.crmType == 'business' && ['business_type', 'business_status'].includes(item.formType)) {
    return false
  } else if (props.crmType == 'contract' && ['business', 'contacts', 'customer'].includes(item.formType)) {
    return false
  } else if (props.crmType == 'receivables' && ['contract', 'customer', 'receivables_plan'].includes(item.formType)) {
    return false
  } else if (props.crmType == 'receivablesPlan' && ['contract', 'customer'].includes(item.formType)) {
    return false
  } else if (props.crmType == 'invoice' && ['contract', 'customer'].includes(item.formType)) {
    return false
  } else if (props.crmType == 'visit' && ['business', 'contract', 'contacts', 'customer'].includes(item.formType)) {
    return false
  } else if (item.formType === 'desc_text' || item.formType === 'handwriting_sign') {
    // 描述文字签名不允许编辑
    return false
  }
  // authLevel 1 不能查看不能编辑 2可查看  3 可编辑可查看
  return item.authLevel === 3 && crm.value && crm.value[props.crmType] && crm.value[props.crmType].update // 不能编辑 disabled true
}

// 编辑
const showSaveButton = ref(false)

/**
 * 点击编辑按钮
 */
function editClick(item, index) {
  let dataValue = objDeepCopy(allForm.value[item.fieldName])
  // 明细表格是空时，需要填充一条空数据，展示时未处理。这里增加
  if (item.formType === 'detail_table' && isEmpty(dataValue)) {
    dataValue = hookCustomFields.getItemValue(objDeepCopy(item), null, 'update')
  }

  //todo whf 这里没有响应式，
  editForm.value[item.fieldName] = dataValue
  item.isEdit = true
  editOptions.value[item.fieldName] = item
  currentEditRules.value[item.fieldName] = editRules.value[item.fieldName] || []
  // this.$set(this.editForm, item.fieldName, dataValue)
  // this.$set(item, 'isEdit', true)
  // this.$set(this.editOptions, item.fieldName, item)
  // this.$set(this.currentEditRules, item.fieldName, this.editRules[item.fieldName] || [])
  showSaveButton.value = true
}

/**
 * 点击取消
 */
function editCancel() {
  console.log("cxt.refs.editForm0", cxt.refs)
  if (cxt.refs.editForm0 && cxt.refs.editForm0[0].clearValidate) {
    cxt.refs.editForm0[0].clearValidate()
  }

  nextTick(() => {
    // this.list.forEach(bItem => {
    //   bItem.list.forEach(item => {
    //     item.isEdit = false
    //   })
    // })
    editFieldData.value.forEach(item => {
      item.isEdit = false
    })

    currentEditRules.value = {}
    editForm.value = {}
    editOptions.value = {}
    showSaveButton.value = false
  })
}

/**
 * 点击保存
 */
function editConfirm() {
  // customerId    fieldId   fieldType  fieldName  formType  value
  // this.editCancel()
  cxt.refs.editForm0[0].validate(valid => {
    if (valid) {
      submitInfo()
    }
  })
}

/**
 * 发请求提交数据
 */
function submitInfo() {
  // 仅第一块可编辑 ，直接取第一块的数据
  loading.value = true
  const list = []
  for (let index = 0; index < editFieldData.value.length; index++) {
    const field = editFieldData.value[index]
    // 获取当前编辑 和 隐藏的字段
    if (field.formType !== 'desc_text' && (field.isEdit || !field.show)) {
      list.push({
        fieldName: field.fieldName,
        fieldType: field.fieldType,
        name: field.name,
        type: field.type,
        fieldId: field.fieldId,
        value: field.show ? hookCustomFields.getRealParams(field, editForm.value[field.fieldName]) : null
      })
    }
  }

  filedUpdateTableFieldAPI({
    id: props.id,
    batchId: props.detail.batchId,
    label: crmTypeModel[props.crmType],
    list: list
  }).then(res => {
    loading.value = false
    emits('handle', {type: 'save-success'}) // 刷新数据
    editCancel()
  }).catch((e) => {
    console.log("e",e)
    loading.value = false
  })
}

/**
 * 员工编辑
 * 关联模块编辑
 * 附件选择
 * 产品类别
 */
function arrayValueChange(data, item) {
  editForm.value[item.fieldName] = data.value || []
}

/**
 * 判断是否显示展示
 */
function getShowValue(item) {
  if (item.hasOwnProperty('show')) {
    return item.show
  }
  return true
}

/**
 * 获取单选值
 */
function getSelectShowValue(data) {
  const field = data.props
  const value = data.value
  if (value !== null) {
    const dataValue = field.setting.find(o => o.value === value)
    return dataValue ? dataValue.name : ''
  }
  return ''
}

</script>

<style lang="scss" scoped>
.b-cont {
  position: relative;
  padding: 15px;
  height: 100%;
  overflow-y: auto;
  overflow-y: overlay;

  &__handle {
    position: absolute;
    text-align: right;
    right: 20px;
    width: 100%;
    z-index: 3;
  }
}

.section {
  margin-top: 0;

  :deep( .content) {
    overflow: hidden;
  }
}

.el-input-number {
  width: 100%;

  :deep(.el-input__inner ) {
    text-align: left;
    padding: 0 8px;
  }
}

.b-cells + .b-cells {
  margin-top: 25px;
}

.b-cell {
  padding: 0 10px;
}

.el-form--flex {
  margin: 20px 10px 0;

  :deep( .el-form-item) {
    padding: 0 40px 0 15px;
    margin-bottom: 10px;
    max-width: 100%;

    .el-form-item__content {
      position: relative;
      min-height: 40px;
      line-height: 1.5;
    }

    .el-form-item__label {
      color: #777;
      font-size: 13px;
      line-height: 1.5;
    }

    &:hover {
      .form-item__edit {
        display: inline;
      }
    }

    &.is-desc_text {
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }
}

.form-item__value {
  font-size: 13px;
  color: #333;
  line-height: 1.5;
  min-height: 22px;
  white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-all;

  .wk-field-view {
    width: 0;
    flex: 1;
  }
}

.form-item__edit {
  margin-left: 5px;
  font-size: 14px;
  color: #999;
  cursor: pointer;
  display: none;
  flex-shrink: 0;

  &:hover {
    color: $xr-color-primary;
  }
}

.can-check {
  color: $xr-color-primary !important;
  cursor: pointer;
}

.is-block {
  flex-basis: 100% !important;
}

.b-cell-b {
  width: auto;

  .b-cell-name {
    width: 100px;
    margin-right: 10px;
    font-size: 13px;
    flex-shrink: 0;
    color: #777;
  }

  .b-cell-value {
    font-size: 13px;
    color: #333;
    line-height: 30px;
    white-space: pre-wrap;
    word-wrap: break-word;
    word-break: break-all;
  }
}
</style>
